package com.net.wanjian.networkhospitalmanager.activity.teacherevent;

import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.net.wanjian.networkhospitalmanager.R;
import com.net.wanjian.networkhospitalmanager.activity.base.BaseActivity;
import com.net.wanjian.networkhospitalmanager.adapter.TeacherEventAdapter;
import com.net.wanjian.networkhospitalmanager.bean.teacherevent.SearchEducatiationByConditionResult;
import com.net.wanjian.networkhospitalmanager.consts.AppConsts;
import com.net.wanjian.networkhospitalmanager.consts.ErrorCodeReturn;
import com.net.wanjian.networkhospitalmanager.model.taggroup.TagsManager;
import com.net.wanjian.networkhospitalmanager.net.HttpUtil;
import com.net.wanjian.networkhospitalmanager.netstatus.NetUtils;
import com.net.wanjian.networkhospitalmanager.utils.ProgressDialogUtils;
import com.net.wanjian.networkhospitalmanager.utils.SharedXmlUtil;
import com.net.wanjian.networkhospitalmanager.utils.ToastUtil;
import com.net.wanjian.networkhospitalmanager.utils.URLDecoderUtil;
import com.net.wanjian.networkhospitalmanager.widge.RefreshRecyclerView;

import java.util.List;

import butterknife.BindView;
import io.reactivex.observers.DisposableObserver;
import me.gujun.android.taggroup.TagGroup;

public class SearchTeacherEventActivity extends BaseActivity {

    @BindView(R.id.search_teacher_event_search_et)
    EditText searchTeacherEventSearchEt;
    @BindView(R.id.search_teacher_event_del_iv)
    ImageView searchTeacherEventDelIv;
    @BindView(R.id.teacher_event_search_taggroup)
    TagGroup teacherEventSearchTaggroup;
    @BindView(R.id.search_teacher_event_deltag_iv)
    ImageView searchTeacherEventDeltagIv;
    @BindView(R.id.search_teacher_recycler_view)
    RefreshRecyclerView refreshRecyclerView;
    @BindView(R.id.search_teacher_layout)
    LinearLayout searchLinearLayout;
    @BindView(R.id.search_teacher_progressbar)
    ProgressBar progressBar;

    private TagsManager mTagsManager;

    private TeacherEventAdapter teacherEventAdapter;
    private List<SearchEducatiationByConditionResult.DataBean.EducationActivityListBean> educationActivityList;
    private int currentNum = AppConsts.currentPageNum, currentPageNum, countNum;

    //    private String[] tags = new String[]{"新生儿感染", "五官科测试", "导尿管相关泌尿感染检测系统流程", "血液科室", "测试用检查", "化验科"};
//    private List<String> tagList = new ArrayList<>();
    private String[] tags;
    private String key;

    @Override
    protected void initData() {
        refreshRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        refreshRecyclerView.setRefreshMode(3);
        refreshRecyclerView.addOnRefreshListener(new RefreshRecyclerView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                searchHttpRequest(key);
            }

            @Override
            public void onLoadMore() {
                loadMore();
            }
        });
        teacherEventAdapter = new TeacherEventAdapter(this);
//        teacherEventAdapter.setList(educationActivityList);
        refreshRecyclerView.setAdapter(teacherEventAdapter);

        setSearchAndListVisibility(false, true);

        mTagsManager = TagsManager.getInstance(getApplicationContext());
        tags = mTagsManager.getTags();

        if (tags != null && tags.length > 0) {
            teacherEventSearchTaggroup.setTags(tags);
        }

        teacherEventSearchTaggroup.setOnTagClickListener(new TagGroup.OnTagClickListener() {
            @Override
            public void onTagClick(String s) {
                //点击标签后掉用搜索方法开始搜索
                key = s;
                searchTeacherEventSearchEt.setText(key);
                searchHttpRequest(key);

            }
        });

        searchTeacherEventDelIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SearchTeacherEventActivity.this.finish();
            }
        });
        searchTeacherEventDeltagIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ProgressDialogUtils.showAskDialog(SearchTeacherEventActivity.this, "", "是否删除全部的历史记录", "确认", "取消", new ProgressDialogUtils.OnClickDialogBtnListenner() {
                    @Override
                    public void onClickDialogBtn(int btnId) {
                        if (btnId == 1) {
                            SearchTeacherEventActivity.this.tags = new String[]{};
                            teacherEventSearchTaggroup.setTags(tags);
                            mTagsManager.clearTags();
                        }
                    }
                }, true);

            }
        });

        searchTeacherEventSearchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    //按下enter后执行搜索操作
                    String s = searchTeacherEventSearchEt.getText().toString();
                    if (!s.isEmpty()) {
                        mTagsManager.addTag(s);
                        //这里掉用搜索方法开始搜索
                        key = s;
                        searchHttpRequest(key);
                    } else {
                        ToastUtil.showToast("请输入搜索关键字");
                    }
                }
                return true;
            }
        });

    }

    //加载更多
    private void loadMore() {
        currentPageNum++;
        SharedXmlUtil xmlUtil = SharedXmlUtil.getInstance();
        HttpUtil.searchEducatiationActivityByKeyword(xmlUtil.getDeviceId(), xmlUtil.getToken(), xmlUtil.getHospitalId(),
                key, currentPageNum, currentNum, new DisposableObserver<SearchEducatiationByConditionResult>() {
                    @Override
                    public void onNext(SearchEducatiationByConditionResult searchEducatiationByConditionResult) {
                        if (searchEducatiationByConditionResult.getResult() == ErrorCodeReturn.success) {
                            SharedXmlUtil.getInstance().setToken(URLDecoderUtil.getDecoder(searchEducatiationByConditionResult.getData().getToken()));
                            educationActivityList.addAll(searchEducatiationByConditionResult.getData().getEducationActivityList());
                            teacherEventAdapter.setList(educationActivityList);

                            if (searchEducatiationByConditionResult.getData().getEducationActivityList().size() < currentNum || educationActivityList.size() >= countNum) {
                                refreshRecyclerView.setNoMore(true);
                            }else {
                                refreshRecyclerView.loadMoreComplete();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        refreshRecyclerView.loadMoreComplete();
                    }

                    @Override
                    public void onComplete() {
                        refreshRecyclerView.loadMoreComplete();
                    }
                });
    }

    private void searchHttpRequest(String keyword) {
        currentPageNum = 0;
        progressBar.setVisibility(View.VISIBLE);
        SharedXmlUtil xmlUtil = SharedXmlUtil.getInstance();
        HttpUtil.searchEducatiationActivityByKeyword(xmlUtil.getDeviceId(), xmlUtil.getToken(), xmlUtil.getHospitalId(),
                keyword, currentPageNum, currentNum, new DisposableObserver<SearchEducatiationByConditionResult>() {
                    @Override
                    public void onNext(SearchEducatiationByConditionResult searchEducatiationByConditionResult) {
                        if (searchEducatiationByConditionResult.getResult() == ErrorCodeReturn.success) {
                            SharedXmlUtil.getInstance().setToken(URLDecoderUtil.getDecoder(searchEducatiationByConditionResult.getData().getToken()));
                            educationActivityList = searchEducatiationByConditionResult.getData().getEducationActivityList();
                            countNum = Integer.parseInt(URLDecoderUtil.getDecoder(searchEducatiationByConditionResult.getData().getEducationActivityCount()));
                            if (countNum == 0) {
                                ToastUtil.showToast("没有匹配的数据");
                                setSearchAndListVisibility(false, true);
                            } else {
                                teacherEventAdapter.setList(educationActivityList);
                                setSearchAndListVisibility(true, false);
                            }

                            if (searchEducatiationByConditionResult.getData().getEducationActivityList().size() < currentNum || educationActivityList.size() >= countNum) {
                                refreshRecyclerView.refreshComplete();
                                refreshRecyclerView.setNoMore(true);
                            } else {
                                refreshRecyclerView.refreshComplete();
                                refreshRecyclerView.setNoMore(false);
                            }

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        progressBar.setVisibility(View.GONE);
                        refreshRecyclerView.refreshComplete();
                    }

                    @Override
                    public void onComplete() {
                        progressBar.setVisibility(View.GONE);
                    }
                });
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_search_teacher_event;
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

    /**
     * 设置是否显示list和search布局
     *
     * @param list
     * @param search
     */
    private void setSearchAndListVisibility(boolean list, boolean search) {
        if (list) {
            refreshRecyclerView.setVisibility(View.VISIBLE);
        } else {
            refreshRecyclerView.setVisibility(View.GONE);
        }

        if (search) {
            searchLinearLayout.setVisibility(View.VISIBLE);
        } else {
            searchLinearLayout.setVisibility(View.GONE);
        }
    }

}
